﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command;
using AuthCenter_HuangJingtao.Read.Api.Dto;
using Dm.util;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler
{
    public class RoleQueryNameCommandHandler : IRequestHandler<RoleQueryNameCommand, ApiResult<List<App>>>
    {
        IBaseReponsitory<Roles> Roles;
        IBaseReponsitory<App> Apps;
        IBaseReponsitory<RoleApp> RoleApp;
        public RoleQueryNameCommandHandler(IBaseReponsitory<Roles> Roles, IBaseReponsitory<App> Apps, IBaseReponsitory<RoleApp> RoleApp)
        {
            this.Roles = Roles;
            this.Apps = Apps;
            this.RoleApp = RoleApp;
        }

        public async Task<ApiResult<List<App>>> Handle(RoleQueryNameCommand request, CancellationToken cancellationToken)
        {

            var slt = await Roles.GetQuery().Where(c => c.Role_Name == request.Name).FirstOrDefaultAsync();//角色表
            var list = await Apps.GetQuery().ToListAsync();//用户表
            List<App> apps = new List<App>();
            foreach (var item in list)
            {
                var arr = item.Role_ArrId.Split(',').Select(int.Parse).ToArray();//结果转化整数再转化数组
                foreach (int role_id in arr)
                {
                    if (role_id == slt.Role_Id)
                    {
                        //每次循环都保存一次到变量
                        apps.Add(item);
                    }
                    else
                    {
                    }
                }
            }
            return new ApiResult<List<App>>
            {
                Code = ApiEnum.Success,
                Message = "查询成功",
                Data = apps
            };

        }
    }
}
